package com.cuitrip.business.tripservice;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.ui.EditTextHolderView;
import com.cuitrip.service.R;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.utils.ArrayUtil;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 段落编辑 activity
 * Created  ak
 */
public class ParaEditActivity extends CustomUiFragmentActivity implements EditTextHolderView.EditTextCallBack {

    public static final String PARA_KEY = "para_key";
    public static final String TITLE_KEY = "title";
    public static final String MAX_LIMIT_KEY = "max_limit";
    private static final String TAG = "TripEditActivity";
    @Bind(R.id.edit_layout)
    protected LinearLayout mEditLayout;
    @Bind(R.id.edit_count)
    protected TextView editCountView;
    protected ServiceInfo serviceInfo;
    @Bind(R.id.click_content)
    View clickContent;
    private int maxLimit = 600;
    private String title;
    private Handler mHandler = new Handler();
    private ArrayList<CharSequence> highLightList = new ArrayList<CharSequence>();
    private ArrayList<EditTextHolderView> editTextHolderViewList = new ArrayList<>();
    private ArrayList<CharSequence> charSequenceList = new ArrayList<>();

    private Handler useHandler = new Handler();

    public static void launchParaEditActivity(Activity activity, Bundle bundle, int requestCode) {
        Intent intent = new Intent(activity, ParaEditActivity.class);
        intent.putExtras(bundle);
        Jumper.launchActivityForResult(activity, intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent.hasExtra(TITLE_KEY)) {
            title = intent.getStringExtra(TITLE_KEY);
        }
        if (intent.hasExtra(ServiceInfo.KEY)) {
            serviceInfo = (ServiceInfo) intent.getSerializableExtra(ServiceInfo.KEY);
        }
        if (intent.hasExtra(PARA_KEY)) {
            ArrayList<CharSequence> paraList = intent.getCharSequenceArrayListExtra(PARA_KEY);
            charSequenceList.clear();
            charSequenceList.addAll(paraList);
        }
        if (intent.hasExtra(MAX_LIMIT_KEY)) {
            maxLimit = intent.getIntExtra(MAX_LIMIT_KEY, 200);
        }
        super.onCreate(savedInstanceState, getLayoutRes());
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        useHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initText();
            }
        }, 100);
    }

    protected
    @LayoutRes
    int getLayoutRes() {
        return R.layout.page_edit_para;
    }


    private void initText() {
        if (charSequenceList == null || charSequenceList.size() == 0) {
            for (int i = 0; i < 1; i++) {
                String content = new String();
                EditTextHolderView editTextHolderView = new EditTextHolderView(this);
                editTextHolderView.bindData(content, i);
                addEdit(editTextHolderView, i);
            }
        } else {
            for (int i = 0; i < charSequenceList.size(); i++) {
                String content = new String(charSequenceList.get(i).toString());
                EditTextHolderView editTextHolderView = new EditTextHolderView(this);
                editTextHolderView.bindData(content, i);
                addEdit(editTextHolderView, i);
            }
        }
        setTextCount(getEditCount());

    }


    @Override
    public void onKeyEnter(EditTextHolderView editTextHolderView) {
        int currentPosition = editTextHolderViewList.indexOf(editTextHolderView);
        if (ArrayUtil.isIndexSafe(currentPosition, editTextHolderViewList)) {
            String content = new String();
            EditTextHolderView newEditTextHolderView = new EditTextHolderView(this);
            newEditTextHolderView.bindData(content, currentPosition + 1);
            addEdit(newEditTextHolderView, currentPosition + 1);
            newEditTextHolderView.requestFocus();
        }

    }

    @Override
    public void onKeyClear(EditTextHolderView editTextHolderView) {
        int currentPosition = editTextHolderViewList.indexOf(editTextHolderView);
        if (ArrayUtil.isIndexSafe(currentPosition, editTextHolderViewList)) {
            if (editTextHolderViewList.size() == 1) {
                return;
            }
            removeEdit(editTextHolderView, currentPosition);
            if (currentPosition > 0) {
                editTextHolderViewList.get(currentPosition - 1).requestFocus();
            } else {
                if (!editTextHolderViewList.isEmpty()) {
                    editTextHolderViewList.get(currentPosition).requestFocus();
                }
            }
        }
    }

    @OnClick(R.id.click_content)
    void editClick() {
        if (!ArrayUtil.isNullOrEmpty(editTextHolderViewList)) {
            final EditTextHolderView editTextHolderView = editTextHolderViewList.get(editTextHolderViewList.size() - 1);

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (editTextHolderView.getEditView().requestFocus() || editTextHolderView.getEditView().requestFocusFromTouch()) {
                        InputMethodManager imm = (InputMethodManager)
                                getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(editTextHolderView.getEditView(), 0);
                        clickContent.setVisibility(View.GONE);
                    }
                }
            }, 100);

        }

    }

    @Override
    public boolean onTextNumberChanged(int number) {
        int editCount = getEditCount();
        if (editCount > maxLimit) {
            setTextCount(editCount);
            return false;
        } else {
            setTextCount(editCount);
            return true;
        }
    }

    public void setMaxLimit(int maxLimit) {
        this.maxLimit = maxLimit;
    }

    private void setTextCount(int editCount) {
        editCountView.setText(editCount + "/" + maxLimit);
    }

    public void addEdit(EditTextHolderView editTextHolderView, int position) {
        editTextHolderViewList.add(position, editTextHolderView);
        mEditLayout.addView(editTextHolderView, position);
        editTextHolderView.setEditTextCallBack(this);
    }

    public void removeEdit(EditTextHolderView editTextHolderView, int position) {
        if (editTextHolderViewList.contains(editTextHolderView)) {
            editTextHolderViewList.remove(position);
            mEditLayout.removeView(editTextHolderView);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.ct_menu_save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:
                if (saveAction()) {
                    finish();
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void saveOtherAction(Intent intent) {

    }

    @Override
    public void onBackPressed() {
        if (saveAction()){
            super.onBackPressed();
        }
    }

    protected boolean saveAction() {
        if (!TextUtils.isEmpty(editTextHolderViewList.get(0).getText())) {
            for (EditTextHolderView editTextHolderView : editTextHolderViewList) {
                String content = editTextHolderView.getText();
                if (TextUtils.isEmpty(content)) {
                    continue;
                }
                highLightList.add(editTextHolderView.getText());
            }
        }
        Intent intent = new Intent();
        intent.putCharSequenceArrayListExtra(PARA_KEY, highLightList);
        saveOtherAction(intent);
        setResult(RESULT_OK, intent);
        return true;
    }

    private int getEditCount() {
        int count = 0;
        for (EditTextHolderView editTextHolderView : editTextHolderViewList) {
            count = count + editTextHolderView.getEditSize();
        }
        return count;
    }

    protected void onDestroy() {
        super.onDestroy();
        hideInput();
    }

    private void hideInput() {
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = title;
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }
}
